package com.hnkywl.sts.webservice.wly.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hnkywl.sts.entity.organ.Qyfr;
import com.hnkywl.sts.entity.organ.Qyjg;
import com.hnkywl.sts.service.base.WebserviceLogService;
import com.hnkywl.sts.service.fxssh.KhfwService;
import com.hnkywl.sts.service.organ.QyfrService;
import com.hnkywl.sts.service.organ.QyjgService;
import com.hnkywl.sts.util.Pinyin;
import com.hnkywl.sts.util.Tools;
import com.hnkywl.sts.webservice.wly.ICustom;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 客户相关接口
 * Created by Fei on 2015/12/8.
 */
@Service
public class CustomService implements ICustom, ApplicationContextAware {
    private ApplicationContext applicationContext;
    private WebserviceLogService webserviceLogService;

    private QyjgService qyjgService;
    private KhfwService khfwService;
    private QyfrService qyfrService;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        qyjgService = (QyjgService) applicationContext.getBean("qyjgService");
        khfwService = (KhfwService) applicationContext.getBean("khfwService");
        qyfrService = (QyfrService) applicationContext.getBean("qyfrService");
        webserviceLogService = (WebserviceLogService) applicationContext.getBean("webserviceLogService");
    }


    /**
     * 新增和修改企业机构信息
     *
     * @param param
     * @return
     */
    @Override
    public String clientFeedBackResponse(String param) {
        String result = "";
        String exception = null;
        try {
            Gson gson = new Gson();
            List<Map<String, Object>> resultList = gson.fromJson(param, new TypeToken<List<Map<String, Object>>>() {
            }.getType());
            if (null != resultList && resultList.size() > 0) {
                for (Map<String, Object> resultMap : resultList) {
                    String name = (String) resultMap.get("name");
                    if (StringUtils.isBlank(name)) {
                        result = "[{\"code\":\"1\",\"message\":\"运营系统返回，企业机构为空！\"}]";
                    } else {
                        Qyjg qyjg = this.qyjgService.findByJc(name);
                        if (qyjg != null) {
                            Qyfr qyfr = qyjg.getQyfr();
                            qyfr.setKhh((String) resultMap.get("open_bank"));
                            qyfr.setZh((String) resultMap.get("account_no"));
                            qyfr.setFddlr((String) resultMap.get("agent"));
                            qyfr.setNsh((String) resultMap.get("tax_no"));
                            qyfr.setDh((String) resultMap.get("tel"));
                            qyfr.setAddress((String) resultMap.get("address"));
                            this.qyfrService.saveQyfr(qyfr);
                            qyjg.setBm((String) resultMap.get("loginID"));
                            qyjg.setZzjgh((String) resultMap.get("organization"));
                            qyjg.setLxr((String) resultMap.get("contactPerson"));
                            qyjg.setLxdh(resultMap.get("tel") + "-" + resultMap.get("phone"));
                            this.qyjgService.updateQyjg(qyjg);
                            result = "[{\"code\":\"0\",\"message\":\"运营系统返回，企业机构更新成功\"}]";
                        } else {
                            Qyfr qyfr = new Qyfr();
                            qyfr.setKhh((String) resultMap.get("open_bank"));
                            qyfr.setZh((String) resultMap.get("account_no"));
                            qyfr.setFddlr((String) resultMap.get("agent"));
                            qyfr.setNsh((String) resultMap.get("tax_no"));
                            qyfr.setDh((String) resultMap.get("tel"));
                            qyfr.setQyqc(name);
                            qyfr.setQyjc(name);
                            qyfr.setAddress((String) resultMap.get("address"));
                            this.qyfrService.saveQyfr(qyfr);
                            qyjg = new Qyjg();
                            qyjg.setBm((String) resultMap.get("loginID"));
                            qyjg.setJc(name);
                            qyjg.setQc(name);
                            qyjg.setZzjgh((String) resultMap.get("organization"));
                            qyjg.setLxr((String) resultMap.get("contactPerson"));
                            qyjg.setLxdh(resultMap.get("tel") + "-" + resultMap.get("phone"));
                            qyjg.setSfzx(false);
                            qyjg.setDeleted(0);
                            qyjg.setZt("ysp");
                            qyjg.setSfzx(false);
                            qyjg.setBzjbl(20.0);
                            qyjg.setZjm(Pinyin.getPinYinHeadChar(name).toUpperCase());
                            qyjg.setDateCreated(new Date());
                            qyjg.setLastUpdated(qyjg.getDateCreated());
                            qyjg.setQyfr(qyfr);
                            qyjg.setSfbggys("1");
                            this.qyjgService.saveQyjg(qyjg);
                            this.qyjgService.saveFkfs(qyjg);
                            result = "[{\"code\":\"0\",\"message\":\"运营系统返回，企业机构创建成功\"}]";
                        }
                    }
                }
            } else {
                result = "[{\"code\":\"1\",\"message\":\"运营系统返回，传入参数为空\"}]";
            }
        } catch (Exception e) {
            exception = e.getMessage();
            result = "[{\"code\":\"1\",\"message\":\"运营系统返回，" + exception + "\"}]";
        }
        try {
            JSONArray jsonArray = new JSONArray(param);
            webserviceLogService.saveServerLog(
                    CustomService.class.getName(),
                    "clientFeedBackResponse",
                    jsonArray.toString(),
                    "返回结果：" + result,
                    exception,
                    ""
            );
        } catch (Exception e) {
            webserviceLogService.saveServerLog(
                    CustomService.class.getName(),
                    "clientFeedBackResponse",
                    param,
                    "返回结果：" + result,
                    exception,
                    ""
            );
        }
        return result;
    }

    /**
     * 查询保证金
     *
     * @param param {"custom_name":"客户全称"}
     * @return
     */
    @Override
    public String queryMargin(String param) {
        String result;
        String exception = null;
        try {
            Gson gson = new Gson();
            Map<String, Object> resultMap = gson.fromJson(param, new TypeToken<Map<String, Object>>() {
            }.getType());
            //获取客户全称
            String khqc = Tools.NullToString(resultMap.get("custom_name")).toString();
            if (StringUtils.isBlank(khqc)) {
                result = "{\"code\":\"1\",\"message\":\"客户名称为空，不能进行查询！\"}";
            } else {
                result = this.khfwService.queryMarginByKhqc(khqc.trim());
            }
        } catch (Exception e) {
            exception = e.getMessage();
            result = "{\"code\":\"1\",\"message\":\"" + exception + "\"}";
        }
        try {
            JSONObject jsonObject = new JSONObject(param);
            webserviceLogService.saveServerLog(
                    CustomService.class.getName(),
                    "queryMargin",
                    jsonObject.toString(),
                    "返回结果：" + result,
                    exception,
                    ""
            );
        } catch (Exception e) {
            webserviceLogService.saveServerLog(
                    CustomService.class.getName(),
                    "queryMargin",
                    param,
                    "返回结果：" + result,
                    exception,
                    ""
            );
        }
        return result;
    }

    /**
     * 计算代理费
     *
     * @param param
     * @return
     */
    @Override
    public String calAgentFee(String param) {
        String result;
        String exception = null;
        try {
            Gson gson = new Gson();
            Map<String, Object> resultMap = gson.fromJson(param, new TypeToken<Map<String, Object>>() {
            }.getType());
            String customName = Tools.NullToString(resultMap.get("custom_name"));
            String payType = Tools.NullToString(resultMap.get("pay_type"));
            String weight = Tools.NullToString(resultMap.get("weight"));
            String sdays = Tools.NullToString(resultMap.get("sdays"));
            String edays = Tools.NullToString(resultMap.get("edays"));
            String checkResult = this.checkCalAgentFee(customName, payType, weight, sdays, edays);
            if (StringUtils.isBlank(checkResult)) {
                result = this.khfwService.countDlf(customName.trim(), Integer.valueOf(payType.trim())
                        , Integer.valueOf(sdays.trim()), Integer.valueOf(edays.trim()), Double.valueOf(weight.trim()));
            } else {
                result = "{\"code\":\"1\",\"agentFee\":\"\",\"message\":\"" + checkResult + "\"}";
            }
        } catch (Exception e) {
            exception = e.getMessage();
            result = "{\"code\":\"1\",\"agentFee\":\"\",\"message\":\"" + e.getMessage() + "\"}";
        }
        try {
            JSONObject jsonObject = new JSONObject(param);
            webserviceLogService.saveServerLog(
                    CustomService.class.getName(),
                    "calAgentFee",
                    jsonObject.toString(),
                    "返回结果：" + result,
                    exception,
                    ""
            );
        } catch (Exception e) {
            webserviceLogService.saveServerLog(
                    CustomService.class.getName(),
                    "calAgentFee",
                    param,
                    "返回结果：" + result,
                    exception,
                    ""
            );
        }
        return result;
    }


    /**
     * 查询代理费规则
     *
     * @param param
     * @return
     */
    public String queryAgentFeeRule(String param) {
        String result;
        String exception = null;
        try {
            Gson gson = new Gson();
            Map<String, Object> resultMap = gson.fromJson(param, new TypeToken<Map<String, Object>>() {
            }.getType());
            //获取客户全称
            String khqc = Tools.NullToString(resultMap.get("custom_name")).toString();
            if (StringUtils.isBlank(khqc)) {
                result = "{\"code\":\"1\",\"message\":\"客户名称为空，不能进行查询！\",\"agentFeeRules\":[]}";
            } else {
                result = this.khfwService.queryAgentFeeRuleByQc(khqc.trim());
            }
        } catch (Exception e) {
            exception = e.getMessage();
            result = "{\"code\":\"1\",\"message\":\"" + exception + "\",\"agentFeeRules\":[]}";
        }
        try {
            JSONObject jsonObject = new JSONObject(param);
            webserviceLogService.saveServerLog(
                    CustomService.class.getName(),
                    "queryAgentFeeRule",
                    jsonObject.toString(),
                    "返回结果：" + result,
                    exception,
                    ""
            );
        } catch (Exception e) {
            webserviceLogService.saveServerLog(
                    CustomService.class.getName(),
                    "queryAgentFeeRule",
                    param,
                    "返回结果：" + result,
                    exception,
                    ""
            );
        }
        return result;
    }

    /**
     * 检查参数是否为空
     *
     * @param customName
     * @param payType
     * @param weight
     * @param sdays
     * @param edays
     */
    private String checkCalAgentFee(String customName, String payType, String weight, String sdays, String edays) {
        String result = "";
        if (StringUtils.isBlank(customName)) {
            result = "客户全称为空";
            return result;
        }

        if (StringUtils.isBlank(payType)) {
            result = "付款类型为空";
            return result;
        } else {
            try {
                Integer pay = Integer.valueOf(payType);
                if (pay != 0 && pay != 1) {
                    result = "付款类型必须是0或者1，payType = " + payType;
                    return result;
                }

            } catch (Exception e) {
                result = "结束天数不是整数，edays = " + edays;
                return result;
            }
        }

        if (StringUtils.isBlank(weight)) {
            result = "合同重量为空";
            return result;
        }

        if (StringUtils.isBlank(sdays)) {
            result = "起始天数为空";
            return result;
        } else {
            try {
                Integer.valueOf(sdays);
            } catch (Exception e) {
                result = "起始天数不是整数，sdays = " + sdays;
                return result;
            }
        }

        if (StringUtils.isBlank(edays)) {
            result = "结束天数为空";
            return result;
        } else {
            try {
                Integer.valueOf(edays);
            } catch (Exception e) {
                result = "结束天数不是整数，edays = " + edays;
                return result;
            }
        }
        return result;
    }
}
